package com.op.teachingliteapp.util.asynctask;

import android.content.Context;
import android.os.AsyncTask;

import com.op.teachingliteapp.util.ToastUtils;
import com.op.teachingliteapp.util.network.NetworkUtils;

public class HttpGetTask extends AsyncTask<Void, Integer, String> {
	private Context context;
	private String path;
	private DialogHelper dialogHelper;
	private OnTaskProcessListener taskListener;
	private boolean runInSilent;

	@Override
	protected String doInBackground(Void... params) {
		String result = "";
		try {
			result = NetworkUtils.HttpGets(path);
		} catch (Exception e) {
			result = "ERROR";
		}
		return result;
	}

	@Override
	public void onCancelled() {
		super.onCancelled();
		if (taskListener != null) {
			taskListener.completed(null);
		}
	}

	@Override
	public void onPreExecute() {
		if (NetworkUtils.isNetworkAvailable(context)) {
			if (!runInSilent) {
				dialogHelper = new DialogHelper(context, this);
				dialogHelper.showProgressDialog();
			}
			if (taskListener != null) {
				taskListener.prepare();
			}
		} else {
			cancel(false);
		}
	}

	@Override
	public void onPostExecute(String result) {
		if (dialogHelper != null) {
			dialogHelper.dismissProgressDialog();
		}
		if (result.equals("ERROR")) {
			ToastUtils.show(context, "服务器当前不可用，请稍后再试...");
		} else if (taskListener != null) {
			taskListener.completed(result);
		}
	}

	public void setTaskListener(OnTaskProcessListener listener) {
		taskListener = listener;
	}

	public HttpGetTask(Context context, String path) {
		this(context, path, false);
	}

	public HttpGetTask(Context context, String path, boolean runInSilent) {
		this.context = context;
		this.path = path;
		this.runInSilent = runInSilent;
	}
}
